package org.dxy.domain.handler.route;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.port.CommandHandler;
import org.dxy.domain.port.repository.IRouteRepository;
import org.dxy.domain.command.route.UpdateRouteCommand;
import org.dxy.domain.model.aggregate.Route;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 更新工艺路线命令处理器
 * @author: dxy
 * @createTime: 2025/6/26 10:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UpdateRouteCommandHandler implements CommandHandler<UpdateRouteCommand, Void> {

    private final IRouteRepository routeRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(UpdateRouteCommand command) {
        Route route = routeRepository.findById(command.routeId());
        if (route == null) {
            log.error("未找到工艺路线，command={}", command);
            return CommandResult.fail("工艺路线不存在");
        }

        try {
            route.update(command);
            routeRepository.save(route);
            route.getDomainEvents().forEach(eventBus::post);
            route.clearDomainEvents();
            
            log.info("更新工艺路线成功, command={}", command);
            return CommandResult.success("更新工艺路线成功");
        } catch (IllegalStateException e) {
            log.warn("更新工艺路线失败，原因：{}", e.getMessage());
            return CommandResult.fail(e.getMessage());
        }
    }
} 